#!/usr/bin/env node

const { VectorSearchService } = require('./build/vector-search.js');

async function diagnoseVectorSearch() {
  console.log('🔍 Vector Search Diagnosis');
  console.log('=' .repeat(40));

  const vectorService = new VectorSearchService();
  
  try {
    console.log('1. Testing Qdrant connection...');
      // 检查 Qdrant 连接
    try {
      const collections = await vectorService.qdrantClient.getCollections();
      console.log('✅ Qdrant connection successful');
      console.log('   Collections count:', collections.collections.length);
    } catch (error) {
      console.log('❌ Qdrant connection failed:', error.message);
      return;
    }

    console.log('\n2. Checking collection status...');
      // 检查集合状态
    try {
      const info = await vectorService.qdrantClient.getCollection('document_chunks');
      console.log('✅ Collection exists');
      console.log('   Points count:', info.points_count);
      console.log('   Vector size:', info.config.params.vectors.size);
    } catch (error) {
      console.log('❌ Collection issue:', error.message);
    }

    console.log('\n3. Testing Ollama embedding...');
      // 测试 Ollama 嵌入
    try {
      const testText = "测试文本嵌入";
      const embedding = await vectorService.generateEmbedding(testText);
      console.log('✅ Ollama embedding successful');
      console.log(`   Embedding dimension: ${embedding.length}`);
      console.log(`   Sample values: [${embedding.slice(0, 5).map(x => x.toFixed(3)).join(', ')}...]`);
    } catch (error) {
      console.log('❌ Ollama embedding failed:', error.message);
    }

    console.log('\n4. Testing search with known content...');
    
    // 搜索已知内容
    const testQueries = [
      '微服务',
      'microservices',
      '架构',
      'architecture'
    ];
    
    for (const query of testQueries) {
      try {
        const results = await vectorService.searchChunks(query, 2);
        console.log(`   "${query}": ${results.length} results`);
        if (results.length > 0) {
          console.log(`     Best score: ${results[0].score.toFixed(3)}`);
        }
      } catch (error) {
        console.log(`   "${query}": Error - ${error.message}`);
      }
    }

    console.log('\n5. Raw collection query...');
      // 直接查询集合
    try {
      const scrollResult = await vectorService.qdrantClient.scroll('document_chunks', {
        limit: 5,
        with_payload: true,
        with_vector: false
      });
      
      console.log(`✅ Found ${scrollResult.points.length} points in collection`);
      for (let i = 0; i < scrollResult.points.length; i++) {
        const point = scrollResult.points[i];
        const preview = point.payload.content.substring(0, 60) + '...';
        console.log(`   ${i + 1}. ID: ${point.id}`);
        console.log(`      File: ${point.payload.filePath}`);
        console.log(`      Content: "${preview}"`);
      }
    } catch (error) {
      console.log('❌ Collection query failed:', error.message);
    }

  } catch (error) {
    console.error('❌ Diagnosis failed:', error);
  }
}

if (require.main === module) {
  diagnoseVectorSearch().catch(console.error);
}
